--[[
 this is a lua module which implementing the 
 wifi manager on the nodemcu platform   
 autor: zhangoneone
 Nov. 2022 
--]]

wifi_mgr = {}

wifi_mgr.ip = '0.0.0.0'
wifi_mgr.nm = '255.255.255.0'
wifi_mgr.gw = '0.0.0.0'
wifi_mgr.mac = '00:00:00:00:00:00'

local monitor_tmr

--wifi.STATION, wifi.SOFTAP, wifi.STATIONAP or wifi.NULLMODE
function wifi_mgr.set_wifi_mode(mode, save)
    local cur_mode
    cur_mode = wifi.getmode()
    if cur_mode == wifi.SOFTAP then
        print("current wifi mode is softAP, start change...\n")
    else
        print("change mode...\n")
    end

    wifi.setmode(mode, save)
end

--connect to Access Point (DO NOT save config to flash)
function wifi_mgr.connect_wifi(ssid, pwd)
    local station_cfg={}
    station_cfg.ssid = ssid
    station_cfg.pwd = pwd
    station_cfg.save = false
    wifi.sta.config(station_cfg)
    wifi.sta.autoconnect(1)
end

function wifi_mgr.get_net_config()
    -- return current IP address, netmask, gateway
    -- 192.168.0.111  255.255.255.0  192.168.0.1
    local ip, nm, gw = wifi.sta.getip()
    local mac = wifi.sta.getmac()
    return ip, nm, gw, mac
end

function wifi_mgr.get_mac()
    --MAC address as string e.g. "18:fe:34:a2:d7:34"
    local str = wifi.sta.getmac()
    return str
end

function wifi_mgr.disconnect_wifi()
    wifi.sta.disconnect()
end

local function wifi_monitor()
    wifi_mgr.ip, wifi_mgr.nm, wifi_mgr.gw, wifi_mgr.mac = wifi_mgr.get_net_config()
    if wifi_mgr.ip ~= nil then
        coroutine.resume(main_co)
        monitor_tmr:interval(2000*10) -- 20秒检查一次网络变动
    end
end

function wifi_mgr.wifi_init(ssid, pwd)
    wifi_mgr.disconnect_wifi()
    wifi_mgr.set_wifi_mode(wifi.STATION, true)
    wifi_mgr.connect_wifi(ssid, pwd)
    wifi_mgr.ip, wifi_mgr.nm, wifi_mgr.gw, wifi_mgr.mac = wifi_mgr.get_net_config()

    -- create timer to poll the ip
    monitor_tmr = tmr.create()
    monitor_tmr:register(2000, tmr.ALARM_AUTO, wifi_monitor)
    monitor_tmr:start()

end

function wifi_mgr.wifi_exit()
    wifi_mgr.disconnect_wifi()
    if monitor_tmr ~= nil then
        monitor_tmr:unregister()
    end
end

return wifi_mgr
